package com.start.workflow.core.manage;

import com.start.common.details.BaseUserDetails;
import com.start.common.entity.StartBaseUser;
import com.start.common.entity.StartDicData;
import com.start.common.std.StartBaseSingleton;
import com.start.common.std.StartSingletonFactory;
import com.start.common.tools.SpringContextTools;
import com.start.security.StartTokenTools;
import com.start.workflow.entity.StartActModelConfig;
import com.start.workflow.common.std.IStartActCarbonCopy;
import com.start.workflow.core.mappers.StartCarbonCopyMapper;
import com.start.workflow.entity.StartActBusinessEntity;
import com.start.workflow.entity.StartCarbonCopyEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 抄送管理
 */
@Slf4j
public class StartActCarbonCopyManage extends StartBaseSingleton<StartActCarbonCopyManage> {
    private final Map<String, IStartActCarbonCopy> candidateLoadMap = new HashMap<>();
    private StartCarbonCopyMapper startCarbonCopyMapper;

    public static StartActCarbonCopyManage getInstance() {
        return StartSingletonFactory.get(StartActCarbonCopyManage.class);
    }

    /**
     * 调用初始化函数
     */
    @Override
    public void init() {
        candidateLoadMap.clear();
        Map<String, IStartActCarbonCopy> beans = SpringContextTools.getBeans(IStartActCarbonCopy.class, false);
        startCarbonCopyMapper = SpringContextTools.getBean(StartCarbonCopyMapper.class);
        if (beans == null || beans.isEmpty()) return;
        for (IStartActCarbonCopy load : beans.values()) {
            String actCandidateType = load.carbonCopyKey();
            if (StringUtils.isAllBlank(actCandidateType)) {
                log.error(load.getClass().getName() + " 未定义 actCandidateType");
                continue;
            }
            if (candidateLoadMap.containsKey(actCandidateType)) {
                IStartActCarbonCopy old = candidateLoadMap.get(actCandidateType);
                log.error(old.getClass().getName() + "," + load.getClass().getName() + "重复类型候选人类型：" + actCandidateType);
                continue;
            }
            candidateLoadMap.put(actCandidateType, load);
        }
    }

    /**
     * 发送抄送
     *
     * @param config
     */
    public void send(StartActModelConfig config, StartActBusinessEntity actBusiness) {
        IStartActCarbonCopy actCarbonCopy = getActCarbonCopy(config);
        if (actCarbonCopy == null) {
            log.error("未找到指定类型加载" + config.getConfKey());
            return;
        }
        List<StartBaseUser> users = actCarbonCopy.load(config.getConfVal());
        if (users == null || users.isEmpty()) return;
        BaseUserDetails currentUser = StartTokenTools.getCurrentUser(false);
        List<StartCarbonCopyEntity> list = new ArrayList<>(users.size());
        for (StartBaseUser user : users) {
            StartCarbonCopyEntity entity = new StartCarbonCopyEntity();
            entity.setActBusId(actBusiness.getId());
            entity.setReceiveStartUserType(user.getStartUserType());
            entity.setReceiveUserId(user.getId());
            entity.setIsRead(0);
            if (currentUser != null) {
                entity.setCreateBy(currentUser.getUserId());
            }
            list.add(entity);
        }
    }

    public IStartActCarbonCopy getActCarbonCopy(StartActModelConfig config) {
        if (!candidateLoadMap.containsKey(config)) {
            return null;
        }
        return candidateLoadMap.get(config.getConfKey());
    }

    /**
     * 获取抄送类管理器字典
     *
     * @return
     */
    public List<StartDicData> getDicData() {
        List<IStartActCarbonCopy> values = getInstance().candidateLoadMap.values().stream()
                .sorted(Comparator.comparingInt(IStartActCarbonCopy::order)).collect(Collectors.toList());
        Map<String, List<StartDicData>> childDicData = values.stream().
                collect(Collectors.groupingBy(IStartActCarbonCopy::categoryKey, Collectors.mapping(e -> {
                    StartDicData dicData = new StartDicData();
                    dicData.setLabel(e.carbonCopyLabel());
                    dicData.setValue(e.carbonCopyKey());
                    dicData.setDesc(e.actSendDesc());
                    dicData.setOrder(e.order());
                    return dicData;
                }, Collectors.toList())));

        List<StartDicData> rootDic = new ArrayList<>();
        for (String key : childDicData.keySet()) {
            IStartActCarbonCopy first = values.stream().filter(e -> Objects.equals(e.categoryKey(), key)).findFirst().get();
            StartDicData root = new StartDicData();
            root.setLabel(first.categoryName());
            root.setValue(first.categoryName());
            root.setOrder(first.order());
            root.setGroups(childDicData.get(key));
            rootDic.add(root);
        }
        return rootDic;
    }
}
